import {
    ExecutionContext,
    ForbiddenException,
    Inject,
    Injectable,
    UnauthorizedException
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import {WebAuthService} from "../../module/web/auth/web-auth.service";

@Injectable()
export class JwtWebAuthGuard extends AuthGuard('jwt-web') {
    constructor(
        @Inject(WebAuthService)
        private readonly webAuthService: WebAuthService,
    ) {
        super();
    }


    // 可以在这里扩展 canActivate
    async canActivate(ctx: ExecutionContext): Promise<boolean> {
        const req = ctx.switchToHttp().getRequest();
        const accessToken = req.get('Authorization');
        if (!accessToken) {
            throw new UnauthorizedException('请重新登录');
        }

        const { payload, error } = await this.webAuthService.parseToken(accessToken);

        if (error === 'expired') {
            throw new UnauthorizedException('登录状态已过期，请重新登录');
        }

        if (error === 'invalid' || !payload) {
            throw new UnauthorizedException('无效的 token');
        }

        // 继续执行 passport-jwt 的验证流程
        return await this.activate(ctx);
    }

    async activate(ctx: ExecutionContext) {
        return super.canActivate(ctx) as boolean;
    }
}
